<template>
  <el-dialog
    :title="id ? '编辑角色' : '新增角色'"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="setdialogVisible"
    :center="true"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="ruleForm.description" type="textarea" placeholder="1-300个字符" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setdialogVisible">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoles, addRole, getRole, setRole } from '@/api/role'
export default {
  props: ['dialogVisible', 'id'],
  data() {
    const validateName = async(rule, value, callback) => {
      const result = await getRoles()
      let isDone = null
      if (this.id) {
        isDone = result.rows.some(item => (item.name === value) && (item.id !== this.id))
      } else {
        isDone = result.rows.some(item => item.name === value)
      }
      isDone ? callback(new Error('该部门名称已存在')) : callback()
    }
    return {
      ruleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  async created() {
    if (this.id) {
      const result = await getRole(this.id)
      this.ruleForm = result
    }
  },
  methods: {
    // 取消
    setdialogVisible() {
      this.$emit('update:dialog-visible', false)
    },
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.id) {
            await setRole(this.id, this.ruleForm)
            try {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.$emit('upDateRoles')
            } catch (error) {
              this.$message.error('修改失败')
            }
          } else {
            try {
              await addRole(this.ruleForm)
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.$emit('upDateRoles')
            } catch (error) {
              this.$message.error('添加失败')
            }
          }
          this.$emit('update:dialog-visible', false)
        }
      })
    }
  }
}
</script>

<style>

</style>
